//
//  OauthViewController.swift
//  SinaBlog
//
//  Created by 有何不可 on 16/1/2.
//  Copyright © 2016年 有何不可. All rights reserved.
//

import UIKit
import SVProgressHUD

class OauthViewController: UIViewController,UIWebViewDelegate {
    
    let webView = UIWebView()
    
    override func loadView() {
        
        setWebView()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        
        setNavigationBarItem()
    }
    
    private func setWebView() {
        
        // 去文档查阅获取要用的接口;https://api.weibo.com/oauth2/authorize?client_id=2759788640&redirect_uri=http://http://www.baidu.com
        let requset = NSURLRequest(URL: NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=2759788640&redirect_uri=http://www.baidu.com")!)
        
        webView.loadRequest(requset)
        
        view = webView
        
        webView.delegate = self
        
    }
    
    private func setNavigationBarItem() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "dimss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autofill")
    }
    
    // MARK: --navigationBar的按钮方法实现;
    @objc private func dimss() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autofill() {
        
        //document.getElementById('userId').value = "c6885030@sina.com",document.getElementById('passwd').value = "4595210"
        
        let str = "document.getElementById('userId').value = \"c6885030@sina.com\",document.getElementById('passwd').value = \"4595210\""
        
        webView.stringByEvaluatingJavaScriptFromString(str)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
    // MARK: - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
    }
    */
    
}

// MARK: --webView的代理方法实现!~

extension OauthViewController {
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //        printLog(request)
        /*
        URL: https://www.baidu.com/?code=cc6c7e334d55b03d8becd9c88f374eaa
        */
        //        print(request.URL?.absoluteString)
        
        if let OKUrlStr = request.URL?.host {
            if OKUrlStr == redirect_Url {
                
                let index = "code=".endIndex
                
                let str = request.URL?.query!.substringFromIndex(index)
                
                //                print(request.URL?.query)
                
                //                print(str)
                
                OauthViewModel.sharedInstance.getToken(str!, success: { () -> () in
                    
                     NSNotificationCenter.defaultCenter().postNotificationName(key, object: nil)
                    
                    }, fail: { (error) -> () in
                        print(error)
                })
                
                return false
            }
        }
        return true
    }
}
